/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Button,
  View,
  Modal,
  TouchableOpacity,
  Linking,
  Image
} from 'react-native';
import Toast from 'react-native-root-toast';
import Head from './head'; 
import MapModal from './modalMap.js';
import Dimensions from 'Dimensions';
import {MapView, MapTypes, MapModule, Geolocation} from 'react-native-baidu-map';
let TestInfo = [
    {'customer_id':'1234',longitude: 118.738408,'latitude': 32.018975,'customer_name':'张小杰','customer_address':'江苏省南京市建邺区河西大街金融城2号楼','mobile_phone':'18110671234'},
    {'customer_id':'1234',longitude: 118.777287,'latitude': 32.060663,'customer_name':'张大杰','customer_address':'江苏省南京市建邺区河西大街金融城3号楼','mobile_phone':''}
]
export default class Nearby extends Component {
    constructor(props){
        super(props);
        this.range = 10000;
        this.state = {
            mapType: MapTypes.NORMAL,
            zoom: 15,
            center: {
                longitude: 118.838408,
                latitude: 32.018975
            },
            trafficEnabled: false,
            baiduHeatMapEnabled: false,
            markers: [{
                            longitude: 118.738408,
                            latitude: 32.018975,
                            title: ""
                        },
                        {
                            longitude: 118.777287,
                            latitude: 32.060663,
                            title: ""
                        }],
            customerInfo : TestInfo,
            customerInfoIndex:0,
            mobilePhone: <View></View>
        };
    }
  
    // componentWillMount() {
    //     Geolocation.getCurrentPosition()
    //     .then((response) => {
    //         // console.warn(JSON.stringify(response));
    //         let longitude = response.longitude;
    //         let latitude = response.latitude;

    //         let ext11_start = latitude - 0.001 * this.range;
    //         let ext11_end = latitude + 0.001 * this.range;
    //         let ext12_start = longitude - 0.001 * this.range;
    //         let ext12_end = longitude + 0.001 * this.range;

    //         //查询附近客户
    //         let m = httpGet.customerAddress(ext11_start, ext11_end, ext12_start, ext12_end, userid, '');
    //         m.then((response) => response.json())
    //         .then((responseJson) => {
    //             // console.warn('responseJson'+JSON.stringify(responseJson))
    //             // if (responseJson.total == 0) {
    //                 if (responseJson.total == 1) {//测试使用  正式的用注释的判断
    //                 Toast.show(responseJson.retmsg == null ? "未查询到附近客户" : responseJson.retmsg, { duration: Toast.durations.SHORT, position: Toast.positions.CENTER });
    //             } else {
    //                 // for(var i = 0; i < responseJson.rows.length; i++){
    //                 let markers = [];
    //                 for(var i = 0; i < TestInfo.length; i++){
    //                     let p ={};
    //                     p.title = TestInfo[i].customer_name;
    //                     p.longitude = TestInfo[i].longitude;
    //                     p.latitude = TestInfo[i].latitude;
    //                     p.type = 2,
    //                     markers[i + 1] = p;
    //                 }
    //                 let center = {
    //                     title:'当前位置',
    //                     longitude: longitude,
    //                     latitude: latitude,
    //                     type: 1,
    //                 };
    //                 markers[0] = center;
    //                 this.setState({
    //                     center: center,
    //                     markers: markers
    //                 });

    //             }
    //         })
    //         .catch((error) => {
    //             //Toast.show(error == null ? "系统异常" : JSON.stringify(error), {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    //             Toast.show("请检查网络设置", { duration: Toast.durations.SHORT, position: Toast.positions.CENTER });
    //         });

    //     })
    //     .catch((error) => {
    //         Toast.show("定位失败", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    //         // console.warn(JSON.stringify("查询失败" + JSON.stringify(error)))
    //     })
    // }
  
    //显示位置信息
    _mapLocation(longitude,latitude){
        //这里获取 点击的那个图标的经纬度 markers匹配一下
        for(var i = 0; i<this.state.customerInfo.length;i++){

            if( this.state.center.longitude != longitude || this.state.center.latitude != latitude){

                if(this.state.customerInfo[i].longitude == longitude && this.state.customerInfo[i].latitude == latitude){
                    this.setState({
                        customerInfoIndex : i  //取下标
                    })

                    //判断手机号码是不是为空
                    if(this.state.customerInfo[i].mobile_phone != '' && this.state.customerInfo[i].mobile_phone.length == 11){
                        this.setState({
                            mobilePhone:
                                    <TouchableOpacity onPress={this.openCall.bind(this, this.state.customerInfo[i].mobile_phone)}  style = {{flexDirection:'row',alignItems:'center',justifyContent:'flex-start',flex:1}}>
                                            <Image
                                                style={styles.icon}
                                                source={require('../images/phone.png')}
                                            />
                                            <Text style = {{fontSize:16}}>{this.state.customerInfo[i].mobile_phone}</Text>
                                    </TouchableOpacity>
                        })
                    }else{
                        this.setState({
                            mobilePhone: <View></View>
                        })
                    }
                    this.refs.mapLocation.showModal();
                }
            }


        }
        
    }

    hiddenConfirmMap(){
        this.refs.mapLocation.hiddenModal();
    }

    showConfirmMap(){
        this.refs.mapLocation.showModal();
    }

    openCall(tel){
        let url = "tel://" + tel;
        Linking.canOpenURL(url).then(supported => {
            if (!supported) {
                // console.warn('Can\'t handle url: ' + url);
            } else {
                return Linking.openURL(url).catch(err => {});
            }
        }).catch(err => {});
    }

    openBaiduMapDirection(){
        let origin = this.state.center;
        let destination = this.state.customerInfo[this.state.customerInfoIndex];
        let url = baidumap.getOpenBaidumapDirectionUrl(origin, destination);
        // console.warn('url>>>>'+url)
        Linking.canOpenURL(url).then(supported => {
            if (!supported) {
                // console.warn('Can\'t handle url: ' + url);
            } else {
                return Linking.openURL(url).catch(err => {});
            }
        }).catch(err => {
            Toast.show("请安装百度地图", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
        });
    }

    render() {
        return (
        <View style={styles.container} >
            <View style={{height: 60}}>
                <Head  title='附近'></Head>
            </View>
            <MapView 
                trafficEnabled={this.state.trafficEnabled}
                baiduHeatMapEnabled={this.state.baiduHeatMapEnabled}
                zoom={this.state.zoom}
                mapType={this.state.mapType}
                center={this.state.center}
                // marker={this.state.marker}
                markers={this.state.markers}
                style={styles.map}
                onMapClick={(e) => { 
                }}
                onMarkerClick={(e)=>{
                    //点击红色图标位置的时候
                    //   console.warn(JSON.stringify(e.position))
                    this._mapLocation(e.position.longitude,e.position.latitude)
                }}
                onMapPoiClick={(e)=>{
                    //点击地图上带有文字的地名或者商店
                }}
                onMapStatusChange={()=>{
                    //地图开始改变的时候   如双击的时候 地图放大 移动 改变了
                }}

                onMapLoaded={()=>{
                    //刚刚加载的时候
                }}
                >
            </MapView>
            <View>
            
            <MapModal ref="mapLocation"   animationType="fade">
                        <View style={styles.mapModals}>
                            <View style={styles.ListTypeTwo} >
                                    <View style = {{flexDirection:'row',alignItems:'center',flex:1,height:50,borderColor:'#ccc',borderRightWidth:1}}>
                                        <Image
                                            style={styles.icon}
                                            source={require('../images/personal.png')}
                                        />
                                        <Text style = {{fontSize:16}}>{this.state.customerInfo[this.state.customerInfoIndex].customer_name}</Text>
                                    </View>

                                    {this.state.mobilePhone}
                                
                            </View>
                        </View> 
                    
                        <View style={styles.mapModals}>
                            <TouchableOpacity onPress={this.openBaiduMapDirection.bind(this)} style={styles.ListType} >
                                    <Image
                                        style={styles.icon}
                                        source={require('../images/location.png')}
                                    />
                                    <Text style = {{width: Dimensions.get('window').width-45,fontSize:16}}>{this.state.customerInfo[this.state.customerInfoIndex].customer_address}</Text>
                            </TouchableOpacity>
                        </View>
            </MapModal>
            </View>
        </View>
        );
    }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    // width: Dimensions.get('window').width,
    // height: Dimensions.get('window').height - 60 - 60, //减头部60，底部50，百度logo20
    flex: 1,
  },
  mapModals:{
        flex:1,
        flexDirection:'row',
        height:50,
        borderBottomWidth:1,
        borderColor:'#ccc',
  },
    icon: {
        width: 25,
        height: 25,
        marginLeft:10,
        marginRight:10
    },
    ListType:{
        flexDirection:'row',
        alignItems: 'center',
        justifyContent:'flex-start',
    },

    ListTypeTwo:{
        flexDirection:'row',
        alignItems: 'center',
        justifyContent:'space-between',
        flex:1
    }
});

